package oop;

/**
 * @ClassName : oop.Demo08
 * @Author : LV88VL
 * @Date: 2021/2/3 16:50
 * @Description : 稀疏数组
 */
public class Demo08 {
    public static void main(String[] args) {
        //创建一个二维数组
        int[][] a = new int[5][5];
        a[3][3] = 1;
        a[1][3] = 1;
        a[2][3] = 2;
        //打印一个二维数组
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                System.out.print(a[i][j]+"\t");
            }
            System.out.println("");
        }
        System.out.println("=======================");
        //计算有多少个有效值
        int sum=0;
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                if(a[i][j]!=0){
                    sum++;
                }
            }
        }
        //创建稀疏数组
        int [][] b= new int[sum+1][3];
        b[0][0]=a.length;
        b[0][1]=a[0].length;
        b[0][2]=sum;
        //将非0数存放进稀疏数组
        int count=0;
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                if (a[i][j] != 0) {
                    count++;
                    b[count][0]=i;
                    b[count][1]=j;
                    b[count][2]=a[i][j];
                }
            }
        }
        for (int i = 0; i < b.length; i++) {
            System.out.print(b[i][0]+"\t"+b[i][1]+"\t"+b[i][2]+"\t");
            System.out.println("");
        }
        System.out.println("=======================");
        //还原稀疏数组
        int [][] c= new int[b[0][0]][b[0][1]];
        for (int i = 1; i < b.length; i++) {
            c[b[i][0]] [b[i][1]]=b[i][2];
        }
        for (int j = 0; j <c.length; j++) {
            for (int w = 0; w <c[0].length; w++) {
                System.out.print(c[j][w]+"\t");
            }
            System.out.println("");
        }
    }
}
